#include "sendudp.h"

sendudp::sendudp(QObject *parent) :
    QObject(parent)
{
    sender = new QUdpSocket(this);
    udpPort = 54545;
    send_time = new QTimer(this);

    connect(send_time, SIGNAL(timeout()),
            this, SLOT(broadIP()));
}

sendudp::~sendudp()
{
   if (sender)
   {
       sender->close();
       sender->deleteLater();
   }

   if (send_time)
   {
       send_time->stop();
       send_time->deleteLater();
   }
}

void sendudp::startBroadIP(int msec)
{
    send_time->start(msec);
}

void sendudp::stopBroadIp()
{
    send_time->stop();
}

void sendudp::setPort(const qint16 &port)
{
    udpPort = port;
}

void sendudp::broadIP()
{
    QString address = getLocalHostIP();
    broadMessage(address);

    qDebug() << address;
}

QString sendudp::getLocalHostIP() const
{
    QList<QNetworkInterface>InterfaceIpList=QNetworkInterface::allInterfaces();
    for(int i = 0; i < InterfaceIpList.length(); i++)
    {
        if(InterfaceIpList[i].isValid())
        {
            foreach(QNetworkAddressEntry addressE , InterfaceIpList[i].addressEntries())
            {
                if(addressE.ip().protocol() == QAbstractSocket::IPv4Protocol
                        &&addressE.broadcast()!= QHostAddress::Null)
                {
                    return addressE.ip().toString();
                }
            }
        }
    }

    return QString("");
}

void sendudp::broadMessage(const QString& msg)
{
    sender->abort();
    sender->bind(udpPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);

    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);

    QString address = getLocalHostIP();
    out << address << msg;

    sender->writeDatagram(data.data(),data.length(),QHostAddress::Broadcast, udpPort);
    qDebug() << address << msg;
}
